package cn.wolfcode.trip.base.controller;

import cn.wolfcode.trip.base.domain.Comment;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ICommentService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    private ICommentService commentService;

    /*
        点评接口
        增加评论
        资源:/comments/{id}
        动作:PUT
        参数:Comment
     */
    @PostMapping("/{id}")
    public Object saveComment(Comment comment) {
        JSONResult result = new JSONResult();
        comment.setCommentator(UserContext.getCurrentUser());
        commentService.saveComment(comment);
        result.setData(comment);
        return result;
    }

    /*
        查看所属内容的评论
        资源:/comments/{id}
        动作:GET
        参数:
     */
    @GetMapping("/{id}")
    public Object listComments(@PathVariable Long id, QueryObject qo) {
        qo.setPageSize(7);
        JSONResult result = new JSONResult();
        return commentService.queryCommentById(id, qo);
    }

    /*
        根据评论人的 id 查看所有TA的评论
        资源:/comments/{id}
        动作:GET
        参数:
     */
    @GetMapping("/{userId}/getCommentAllByUserId")
    public Object selectCommentAllByUserId(@PathVariable Long userId, QueryObject qo) {
        qo.setPageSize(5);
        qo.setOrderBy("c.time desc");
        PageInfo<Comment> info = commentService.selectCommentAllByUserId(userId, qo);
        List<Comment> list = new ArrayList<>();
        for (Comment comment : info.getList()) {
            if (comment.getTravel() != null) {
                comment.setAllComments(comment.getTravel());
                list.add(comment);
            } else if (comment.getStrategy() != null) {
                comment.setAllComments(comment.getStrategy());
                list.add(comment);
            } else if (comment.getNews() != null) {
                comment.setAllComments(comment.getNews());
                list.add(comment);
            } else if (comment.getHotel() != null) {
                comment.setAllComments(comment.getHotel());
                list.add(comment);
            }
        }
        info.setList(list);
        return info;
    }

    // 根据人物 id 查询TA一共有多少条评论
    @GetMapping("/{userId}/getCount")
    public Object getCommentCountByUserId(@PathVariable Long userId) {
        return commentService.getCommentCountByUserId(userId);
    }


}
